<?php
namespace Dev\Controller;
use Common\Model\GameModel;
use Common\Model\UtilsModel;
use Dev\BaseController;
use Common\Model\QipaiModel;
use Common\Model\CommonModel;
use Think\Controller;
use Think\Model\MongoModel;
class GameController extends BaseController {

    const BIND_IN_MONGO      =1;//在mongo.userinfo.market.child绑定
    const BIND_IN_MYSQL     =2;//在mysql.user_child_join中绑定


    public function dash(){
        
        $data=GameModel::getDash();
        $this->smarty->assign('data',$data);
        $this->smarty->display('Dash.html');
    }


    /*
     * 代理统计界面
     */
    public function agentCountView(){
        $this->smarty->display('AgentAccount.html');
    }




    /**
     * 代理统计,注册时间，操作时间
     */
    public function agentCount(){
        $createDate =I('post.createDate',null);
        $createDate2=I('post.createDate2',null);
        $gameDate   =I('post.gameDate',null);
        $gameDate2  =I('post.gameDate2',null);


        if ($createDate){
            $createBegin=strtotime($createDate);
        }else{
            $createBegin=0;
        }
        if ($createDate2){
            $createEnd=strtotime($createDate2)+UtilsModel::ONE_DAY;
        }else{
            $createEnd=time();
        }



        if ($gameDate){
            $gameBegin=strtotime($gameDate);
        }else{
            $gameBegin=0;
        }
        if ($gameDate2){
            $gameEnd=strtotime($gameDate2)+UtilsModel::ONE_DAY;
        }else{
            $gameEnd=time();
        }



        set_time_limit(90000);
        ini_set('memory_limit','500M');


        $userM=M('users',null,'mysql_'.$this->currentGame);
        $agent=$userM->where("is_agent=1")->field('id,name')->select();

        $agentId=array();
        $agentInfo=array();
        foreach ($agent as $one){
            $agentId[]=$one['id'];

            $agentInfo[$one['id']]=$one;
            $agentInfo[$one['id']]['child']     =0;  //下线数量
            $agentInfo[$one['id']]['room']      =0;  //开房数
            $agentInfo[$one['id']]['diamond']   =0;  //消耗钻石
            $agentInfo[$one['id']]['times']     =0;  //下线开局数
            $agentInfo[$one['id']]['player']    =0;  //开局玩家
            $agentInfo[$one['id']]['rechargeMoney']    =0;  //充值金额
            $agentInfo[$one['id']]['rechargeDiamond']    =0;  //充值钻石

        }
        $mongoUser = new QipaiModel("userinfo", null, 'mongo_'.$this->currentGame);
        $users = array();

        $bindType=self::BIND_IN_MYSQL;
        if($bindType==self::BIND_IN_MONGO){
            $agentIdStr = implode(',', $agentId);
            $mongoCode = 'db.getCollection("userinfo").find({"uid":{$in:[' . $agentIdStr . ']}},{"uid":1,"marketing.child":1,"_id":0}).toArray()';
            $childs = $mongoUser->mongoCode($mongoCode);
            foreach ($childs as $child) {
                foreach ($child['marketing']['child'] as $uid => $info) {
                    if ($info['invitetime'] >= $createBegin && $info['invitetime'] <= $createEnd) {    //加入日期判断
                        $users[$uid] = array();
                        $users[$uid]['uid'] = $uid;
                        $users[$uid]['nickname'] = $info['nickname'];
                        $users[$uid]['times'] = 0;
                        $users[$uid]['room'] = 0;
                        $users[$uid]['diamond'] = 0;
                        $users[$uid]['agent'] = $child['uid'];
                        $users[$uid]['agentName'] = $agentInfo[$users[$uid]['agent']]['name'];

                        $agentInfo[$child['uid']]['child'] += 1;//下线数量+1
                    }
                }
            }
        }
        else{
            $userM  = M('user_child_join',null,'mysql_'.$this->currentGame);
            $begin  = date('Y-m-d H:i:s',$createBegin);
            $end    = date('Y-m-d H:i:s',$createEnd);
            $childs = $userM->where('user_id in ('.implode(',',$agentId).") and status=1 and create_time between '{$begin}' and '{$end}'")->field('user_id,child_user_id')->select();

            foreach($childs as $child){
                $uid                    =(int)$child['child_user_id'];
                $users[$uid]            = array();
                $users[$uid]['uid']     = $uid;
                $users[$uid]['nickname']= '';
                $users[$uid]['times']   = 0;
                $users[$uid]['room']    = 0;
                $users[$uid]['diamond'] = 0;
                $users[$uid]['agent']   = (int)$child['user_id'];
                $users[$uid]['agentName']= $agentInfo[$users[$uid]['agent']]['name'];
                $users[$uid]['rechargeMoney']    =0;  //充值金额
                $users[$uid]['rechargeDiamond']    =0;  //充值钻石

                $agentInfo[$child['user_id']]['child']+=1;//下线数量+1

            }

        }


        //开房数统计
        $mongoCode='db.getCollection("globalroomdata").aggregate([{$match:{"createtime":{$gte:' . $gameBegin . ',$lte:' . $gameEnd . '}}},{$group:{_id:"$owner","room":{$sum:1}}}]).toArray()';
        $re = $mongoUser->mongoCode($mongoCode);
        if(count($re)==0){
        }else{
            foreach ($re as $one){
                $uid = (int)$one['_id'];
                if(!array_key_exists($uid,$users)){
                    continue;
                }
                $users[$uid]['room']=$one['room'];
                $agentInfo[$users[$uid]['agent']]['room']+=$one['room'];//下线开房数累加
            }
        }

        //db.getCollection("newItemsHistory").aggregate([{$match:{"uid":{$in:[22328102,22328153,22328154,22328365,22328103,22329774,22328419,22325067,22329248,22284229,22331531,22328110,22332600,22332698,22298329,22329012,22338057,22328098,22340613,22325036,22328112,22342543,22342625,22342642,22342717,22342573,22342821,22342891,22342894,22342919,22343026,22342496,22343071,22343074,22328764,22328111,22343472,22343477,22337127,22343614,22328343,22328433,22344429,22343406,22344472,22344490,22344511,22344513,22344520,22329192,22328726,22344628,22344983,22344885,22345915,22345927,22345928,22345930,22345935,22345945,22345964,22345966,22345977,22345986,22345990,22346010,22346031,22346047,22346146,22346295,22346353,22346533,22346585,22347119,22347139,22347185,22347248,22347265,22347385,22347388,22347394,22347931,22348034,22348155,22348246,22348384,22348412,22348466,22348514,22348695,22348700,22348710,22348722,22348788,22350088,22329023,22349886,22353362,22353375,22353377,22353419,22353426,22329073,22341758,22330637,22319844,22356329,22355738,22356714,22297209,22322223,22357243,22357250,22357254,22357255,22357258,22357263,22357267,22357270,22357282,22357287,22357312,22328205,22358924,22328674,22352023,22362728,22312737,22336664,22330913,22364051,22352580,22350830,22365691,22366044,22367707,22365326,22335583,22368928,22371029,22372939,22330571,22377008,22367989,22369467,22376787,22380576,22380554,22383121,22384656,22388591,22397941,22377438,22338317,22332590,22402771,22305439,22389703,22400461,22407737,22407424,22409127,22410397,22410981,22411626,22411650,22408125,22413450,22412612,22414010]}"itemid":2,"diff":{$lt:0},"timestamp":{$gte:1506268800,$lte:1506355200}}},{$group:{"_id":"$uid","diamond":{$sum:"$diff"}}}])
        //消耗统计
        $mongoCode ='db.getCollection("newItemsHistory").aggregate([{$match:{"itemid":2,"diff":{$lt:0},"timestamp":{$gte:'.$gameBegin.',$lte:'.$gameEnd.'}}},{$group:{"_id":"$uid","diamond":{$sum:"$diff"}}}]).toArray()';
        $re = $mongoUser->mongoCode($mongoCode);


        $ag=0;
        $other  = 0;
        $total  = 0;
        if(count($re)==0){
        }else{
            foreach ($re as $one){
                $uid = (int)$one['_id'];

                $diamond=abs($one['diamond']);
                $total +=$diamond;
                if(!array_key_exists($uid,$users)){
                    $other +=$diamond;
                    continue;
                }
                $ag +=$diamond;
                $users[$uid]['diamond']=$diamond;
                $agentInfo[$users[$uid]['agent']]['diamond']+=$diamond;//下线钻石消耗数累加
            }
        }



        //充值

        $gameDateTimeBegin  = date('Y-m-d H:i:s',$gameBegin);
        $gameDateTimeEnd    = date('Y-m-d H:i:s',$gameEnd);

        $orderM=M('orders',null,'mysql_'.$this->currentGame);
        $rechargeArr=$orderM->where(" order_status=4 and create_time BETWEEN '{$gameDateTimeBegin}' and '{$gameDateTimeEnd}'")
            ->group("user_id")
            ->field("user_id,sum(summary_diamond_quantity) as rechargeDiamond,sum(summary_cost) as rechargeMoney")
            ->select();

        foreach($rechargeArr as $one){
            $uid=(int)$one['user_id'];
            if(!array_key_exists($uid,$users)){
                continue;
            }
            $users[$uid]['rechargeMoney']=$one['rechargeMoney']/100;
            $agentInfo[$users[$uid]['agent']]['rechargeMoney']+=$one['rechargeMoney']/100;

            $users[$uid]['rechargeDiamond']=$one['rechargeDiamond'];
            $agentInfo[$users[$uid]['agent']]['rechargeDiamond']+=$one['rechargeDiamond'];
        }



        echo "代理下线:",$ag,"<br />非代理玩家消耗 :",$other,"<br />总共",$total;

        //钻石总消耗数
        //db.getCollection('newItemsHistory').aggregate([{$match:{"timestamp":{$gte:1504713600,$lte:1504800000},"itemid":2,"diff":{$lt:0}}},{$group:{"_id":1,"sum":{$sum:"$diff"}}} ])

        foreach($users as $uid=>$v) {
//            //局数统计
//            $mongoCode = 'db.getCollection("globalroomdata").aggregate([{$match:{"createtime":{$gte:' . $gameBegin . ',$lte:' . $gameEnd . '},"history.position.' . $uid . '":{$exists:true}}},{$group:{_id:"1","times":{$sum:"$curgamenbr"}}}])';
//            $re = $mongoUser->mongoCode($mongoCode);
//            if(count($re['_batch'])==0){
//            }else{
//                $users[$uid]['times']=$re['_batch'][0]['times'];
//                $agentInfo[$users[$uid]['agent']]['times']+=$users[$uid]['times'];//下线开局数累加
//                $agentInfo[$users[$uid]['agent']]['player']+=1;//开局玩家+1
//            }
        }

        $file1=CommonModel::exportExcel($users,array('编号','名称','开局数','开房数','消耗钻石','代理编号','代理名称','充值金额','充值钻石'),'user',"玩家");
        $file2=CommonModel::exportExcel($agentInfo,array('编号','名称','下线数量','开房数','消耗钻石','下线开局数','有开局下家','充值金额','充值钻石'),'agent',"代理");
        echo "点击下载:<a href='{$file1}' target='_blank'>玩家</a> &nbsp;&nbsp;";
        echo "<a href='{$file2}' target='_blank'>代理</a>";

//        echo "<table border='1'>";
//        echo "<thead><tr><td>编号</td><td>名称</td><td>开局数</td><td>代理编号</td><td>代理名称</td></tr></thead>";
//        foreach ($users as $uid=>$v){
//            echo "<tr>";
//            echo '<td>',$uid,'</td><td>',$v['nickname'],'</td><td>',$v['times'],'</td><td>',$v['agent'],'</td><td>',$agentInfo[$v['agent']]['name'],'</td>';
//            echo "</tr>";
//        }
//        echo "</table>";
//
//
//
//        echo "<table border='1'>";
//        echo "<thead><tr><td>编号</td><td>名称</td><td>下线数量</td><td>下线开局数</td><td>有开局下家</td></tr></thead>";
//        foreach ($agentInfo as $uid=>$v){
//            echo "<tr>";
//            echo '<td>',$uid,'</td><td>',$v['name'],'</td><td>',$v['child'],'</td><td>',$v['times'],'</td><td>',$v['player'],'</td>';
//            echo "</tr>";
//        }
//        echo "</table>";

//
//        $s = $d->field("uid,marketing.child")->limit("10,2")->select();
//        echo "<pre>";
//        var_dump($s);
//        echo "</pre>";
//        $Model = new \Think\Model\MongoModel("userinfo",null,'mongo');
//        $s = $Model->limit("10,8")->select();
//        var_dump($s);
    }



    /**
     * 每日统计报表
     */
    public function doDailyCount(){
        set_time_limit(0);
        ini_set('memory_limit','500M');

        $date=I("get.date",null);
        $game=I("get.g",null);
        if (!$game){
            echo "failure";
            die;
        }
        $game=strtolower($game);
        $gameKV=GameModel::getGameKv();
        if(!array_key_exists($game,$gameKV)){
            echo "wrong game";
            die;
        }

        GameModel::dailyCount($game,$date);
        echo 'success';
        die;
    }


    /**
     * 每月统计报表
     */
    public function doMonthlyCount(){
        set_time_limit(0);
        ini_set('memory_limit','500M');

        $date=I("get.date",null);
        $game=I("get.g",null);
        if (!$game){
            echo "failure";
            die;
        }
        $game=strtolower($game);
        $gameKV=GameModel::getGameKv();
        if(!array_key_exists($game,$gameKV)){
            echo "wrong game";
            die;
        }

        GameModel::monthlyCount($game,$date);
        echo 'success';
        die;
    }


    
    
    
    /**
     * 每日统计
     */
    public function getDailyCount(){
        $query=I('post.query',0,'int');

        $gameKv=GameModel::getGameKv();
        $this->smarty->assign('gameKv',$gameKv);

        if(!$query) {
            $data = GameModel::getDailyCount(null,null,null,1,30);
            $this->smarty->assign('data',$data);

            $this->smarty->assign('data',$data['data']);
            $this->smarty->assign('recordCount',$data['recordCount']);
            $this->smarty->assign('page',$data['page']);
            $this->smarty->assign('pageCount',$data['pageCount']);

            $this->smarty->display('DailyCount.html');
        }else{
            $game=I('post.game');
            $gameKv=GameModel::getGameKv();
            if(!array_key_exists($game,$gameKv)){
                $game=null;
            }
            $page=I('post.page',1,'int');
            $beginDate=I('post.begin');
            $endDate=I('post.end');
            
            $data = GameModel::getDailyCount($game,$beginDate,$endDate,$page,30);

            $this->smarty->assign('data',$data['data']);
            $this->smarty->assign('recordCount',$data['recordCount']);
            $this->smarty->assign('page',$data['page']);
            $this->smarty->assign('pageCount',$data['pageCount']);

            $html=$this->smarty->fetch('DailyCount_list.html');
            $page=$this->smarty->fetch("pager.html");
            $data=array(
                'status'=>0,
                'html'=>$html,
                'page'=>$page
            );
            echo json_encode($data);
        }

    }

    /**
     * 每月统计
     */
    public function getMonthlyCount(){
        $query=I('post.query',0,'int');

        $gameKv=GameModel::getGameKv();
        $this->smarty->assign('gameKv',$gameKv);

        if(!$query) {
            $data = GameModel::getMonthlyCount(null,null,null,1,30);
            $this->smarty->assign('data',$data);

            $this->smarty->assign('data',$data['data']);
            $this->smarty->assign('recordCount',$data['recordCount']);
            $this->smarty->assign('page',$data['page']);
            $this->smarty->assign('pageCount',$data['pageCount']);

            $this->smarty->display('MonthlyCount.html');
        }else{
            $game=I('post.game');
            $gameKv=GameModel::getGameKv();
            if(!array_key_exists($game,$gameKv)){
                $game=null;
            }
            $page=I('post.page',1,'int');
            $beginDate=I('post.begin');
            $endDate=I('post.end');

            $data = GameModel::getMonthlyCount($game,$beginDate,$endDate,$page,30);

            $this->smarty->assign('data',$data['data']);
            $this->smarty->assign('recordCount',$data['recordCount']);
            $this->smarty->assign('page',$data['page']);
            $this->smarty->assign('pageCount',$data['pageCount']);

            $html=$this->smarty->fetch('MonthlyCount_list.html');
            $page=$this->smarty->fetch("pager.html");
            $data=array(
                'status'=>0,
                'html'=>$html,
                'page'=>$page
            );
            echo json_encode($data);
        }

    }




    /**
     * 代理分成统计
     */
    public function getAgentBenefit(){
        $plat=$this->currentGame;
        $date=I('post.end');
        $agent=I('post.agent',0,'int');
        $endtimestamp=strtotime($date);
        if($endtimestamp){
            $endtimestamp +=UtilsModel::ONE_DAY;
        }else{
            $endtimestamp=0;
        }


        $data=GameModel::agentBenefit($plat,$agent,$endtimestamp);
        $this->smarty->assign('data',$data);
//        if (IS_AJAX){
//            $this->smarty->display('AgentBenefit_data.html');
//        }else{
            $this->smarty->display('AgentBenefit.html');
 //       }
    }



    /**
     * 代理结算
     */
    public function agentPayDo(){
        $agentId    =I('post.agentID',0,'int');
        $money      =I('post.money',0,'float');

        $return=GameModel::agentBenefitProcess($this->currentGame,$agentId,$money,$this->operatorID);
        if($return['status']!=0){
            $this->ajaxReturn($return);
        }

        $this->ajaxReturn(array(
            'status'=>0,
            'msg'=>'success',
            'id'=>$agentId,
            'money'=>$money
        ));
    }


    /**
     * 代理提现记录
     */
    public function agentExtractLog(){
        $agentId=I('get.agentId',0,'int');

        $data=GameModel::getAgentExtractLog($agentId,$this->currentGame);
        $this->smarty->assign('data',$data);

        $agentKv=GameModel::getAgentKv($this->currentGame);
        $this->smarty->assign('agentKV',$agentKv);

        $payType=GameModel::getPayTypeKv($this->currentGame);
        $this->smarty->assign('payType',$payType);

        $this->smarty->assign('done',GameModel::PROCESS_DONE);

        $this->smarty->display('AgentExtractLog.html');
    }
    
    public function getLowerAgentstat(){
        $data=GameModel::getLowerAgentstat($this->currentGame);
        $this->smarty->assign('data',$data);
        
        $this->smarty->display('AgentLower.html');
    }



    public function agentCount2(){
        $data=GameModel::getAgentCount($this->currentGame);
        $this->smarty->assign('data',$data);

        $this->smarty->display('AgentCount.html');
    }


    /**
     * 用户详情
     */
    public function getUserList(){
        $agent=I('get.agent',0,'int');
        if(!$agent){
            $agent=I('post.agent',0,'int');
        }

        $userid=I('post.userid',0,'int');

        $begin  =I('post.begin');
        $end    =I('post.end');

        $beginTimestamp =strtotime($begin)+0;
        $endTimestamp   =strtotime($end)+UtilsModel::ONE_DAY;

        $page=I('post.page',1,'int');
        $export=I('post.export',0,'int');
        $query=I('post.query',0,'int');

        if ($export){
            GameModel::exportUserListAll($this->currentGame,$agent,$beginTimestamp,$endTimestamp,$userid);
            die;
        }

        $data=GameModel::getUserList($this->currentGame,$agent,$beginTimestamp,$endTimestamp,$userid,$page);

        $this->smarty->assign('data',$data['data']);
        $this->smarty->assign('agent',$agent);
        $this->smarty->assign('recordCount',$data['recordCount']);
        $this->smarty->assign('page',$page);
        $this->smarty->assign('pageCount',$data['pageCount']);


        if ($query){//数据
            $html=$this->smarty->fetch('UserCount_data.html');
            $page=$this->smarty->fetch("pager.html");
            $data=array(
                'status'=>0,
                'html'=>$html,
                'page'=>$page
            );
            echo json_encode($data);
        }else{
            $this->smarty->display('UserCount.html');
        }
    }
}